<?php

namespace backend\controllers;

use common\models\Comment;
use common\models\Cooperate;
use common\models\Post;
use common\models\Userr;
use Yii;
use common\models\User;
use common\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\ViewAction;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],

            'access' =>[
                'class' => AccessControl::className(),
                'rules' =>
                    [
                        [
                            'actions' => [ ],
                            'allow' => true,
                            'roles' => ['@'],
                        ],
                        [
                            'actions' => ['view', 'index', 'create','update'],
                            'allow' => true,
                            'roles' => ['@'],
                        ],
                    ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $user = new Userr();
        $dataProvider = $user->search(YII::$app->request->get());
        return $this->render('index', [
            'searchModel' => $user,
            'dataProvider' => $dataProvider,
        ]);
    }

    //消息推荐
    public function actionUpd()
    {
        $token = $this->getToken();
        $ul = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$token;
        //  $token = $this->getToken();

        $user = Userr::find()->select(['openid'])->all();
        $ary = [];
        $arr= [];
        foreach ($user as $k => $v) {
            $ary[] = $v['openid'];
        }

        $con = "你好啊~~"."<a href='http://xiaochaoyang.cn/Blog/frontend/web/index.php'>文章更新啦，点击即可以阅读</a>";

        $arr['msgtype'] = 'text';
        $arr['text']['content']  = $con;
        $arr['touser'] =$ary;
        $ch = curl_init();
        $data_string = json_encode($arr,JSON_UNESCAPED_UNICODE);
        curl_setopt($ch, CURLOPT_URL, $ul);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $info = curl_exec($ch);
        $res = json_decode($info,true);
        if ($res['errcode'] == 0 || $res['errcode'] == 45065){
            return json_encode(['status' => 200, 'msg' => '推送成功']);
        }else{
            return json_encode(['status' => 400, 'msg' => '推送失败']);
        }

    }

    public function getToken()
    {
        $appid = "wx7646ca6bb92fa339";
        $appsecret = "2584e088977867de01b1015def0ea45d";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);
        $access_token = $jsoninfo["access_token"];
        return $access_token;
    }
    public function actionSend(){
        $template_id = '4Kp7cQuLRuFl48Aifq9F6i88VwpB3cdbViZmXYDuWCI';
        $param =   $param = Yii::$app->request->get();
        if (empty($param)){
            return json_encode(['status' => 400, 'msg' => '请求出错']);
        }
        Comment::updateAll(['status' => 3], ['id'=> $param['id']]);
        $comom = Comment::find()->where(['id'=>$param['id']])->one();

        $post = Post::find()->where(['id'=>$comom['post_id']])->one();
        $user = Userr::find()->where(['id'=>$comom['userid']])->one();

        $data['touser'] = $user['openid'];
        $data['template_id'] = $template_id;
        $arr = [];
        $arr ['first']['value'] = '恭喜你成功留言';
        $arr ['first']['color'] = '#173177';

        $arr ['post']['value'] = $post['title'];
        $arr ['post']['color'] = '#173177';

        $arr ['you']['value'] = $comom['content'];
        $arr ['you']['color'] = '#173177';

        $arr ['me']['value'] = $param['text'];
        $arr ['me']['color'] = '#173177';
        $data['data'] = $arr;
        $arr = json_encode($data,JSON_UNESCAPED_UNICODE);

        $token = $this->getToken();
        $ul = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $ul);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $info = curl_exec($ch);
        $res = json_decode($info,true);
       if ($res['errcode'] == 0){
           return json_encode(['status' => 200, 'msg' => '回复成功']);
       }

    }
    public function actionForbidden($id){
        $user = Userr::find()->where(['id'=>$id])->one();
        if ($user->status == 0){
            $user->status = 1;
            $user->save();
        }else{
            $user->status = 0;
            $user->save();
        }
        return $this->redirect(['index']);


    }
    public function actionCoosend(){
        $template_id = 'fkxxOWNI72kTsU12MRIegQA-JQGS3j5JTwi4ab9skyg';
        $param =   $param = Yii::$app->request->get();
        if (empty($param)){
            return json_encode(['status' => 400, 'msg' => '请求出错']);
        }

        $coo = Cooperate::find()->where(['id'=>$param['id']])->one();
        $coo ->status = 1;
        $coo->save();

        $data['touser'] = $coo['openid'];
        $data['template_id'] = $template_id;
        $arr = [];
        $arr ['first']['value'] = '您的合合作信息收到了';
        $arr ['first']['color'] = '#173177';

        $arr ['post']['value'] = $coo['content'];
        $arr ['post']['color'] = '#173177';

        $arr ['me']['value'] = $param['text'];
        $arr ['me']['color'] = '#173177';

        $arr ['time']['value'] =date("Y-m-d");
        $arr ['time']['color'] = '#173177';
        $data['data'] = $arr;
        $arr = json_encode($data,JSON_UNESCAPED_UNICODE);

        $token = $this->getToken();
        $ul = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $ul);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $info = curl_exec($ch);
        $res = json_decode($info,true);
        if ($res['errcode'] == 0){
            return json_encode(['status' => 200, 'msg' => '回复成功']);
        }

    }


}
